package com.myblog.config.security;

import com.myblog.config.filter.ImageCodeValidateFailter;
import com.myblog.config.filter.MobileCodeValidateFailter;
import com.myblog.config.properties.SecurityProperties;
import com.myblog.config.security.authorize.AuthorizeConfigureProviderManager;
import com.myblog.config.security.handle.CustomAuhtenticationFailureHandler;
import com.myblog.config.security.handle.CustomAuhtenticationSuccessHandler;
import com.myblog.config.security.handle.CustomInvalidSessionHandle;
import com.myblog.config.security.handle.CustomLogoutHandler;
import com.myblog.service.impl.CustomUserDetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.sql.DataSource;

@Configuration
@Slf4j
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启注解方法级别控制 连service dao都可以控制
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CustomUserDetailService custormUserDetailService;

    @Autowired
    private CustomAuhtenticationSuccessHandler customAuhtenticationSuccessHandler;

    @Autowired
    private CustomAuhtenticationFailureHandler customAuhtenticationFailureHandler;

    @Autowired
    ImageCodeValidateFailter imageCodeValidateFailter;

    @Autowired
    MobileCodeValidateFailter mobileCodeValidateFailter;

    @Autowired
    private DataSource dataSource;

    @Autowired //由于这个接口只有一个实现类 所以可以直接以接口形式注入
    private AuthorizeConfigureProviderManager authorizeConfigureProviderManager;

    //校验手机验证码
    @Autowired
    private MobileAuthenticationConfig mobileAuthenticationConfig;

    @Autowired
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }


    @Bean
    public JdbcTokenRepositoryImpl jdbcTokenRepository() throws Exception {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //是否启动创建表 第一次启动创建就行 因为后面启动会报表已经存在
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(custormUserDetailService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(securityProperties.getStaticPaths());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(mobileCodeValidateFailter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(imageCodeValidateFailter, UsernamePasswordAuthenticationFilter.class).
                formLogin().loginPage(securityProperties.getLoginPage())
                .loginProcessingUrl(securityProperties.getLoginProcessingUrl())
                .usernameParameter(securityProperties.getUsernameParameter())
                .passwordParameter(securityProperties.getPasswordParameter())
                .successHandler(customAuhtenticationSuccessHandler)
                .failureHandler(customAuhtenticationFailureHandler)
                //关闭csrf跨站 就可以使用get请求的退出
//                .authorizeRequests()
//                .antMatchers(securityProperties.getLoginPage(), "/code/image", "/code/mobile", "/mobile/page").permitAll()
//                .antMatchers("/user").hasAuthority("sys:user")
//                //这种形式的要前面拼接ROLE_比如 ROLE_role
//                //.antMatchers("/role").hasRole("role")
//                .anyRequest()
//                .authenticated()
//                .and()
                .and()
                .rememberMe()
                .tokenRepository(jdbcTokenRepository())
                .tokenValiditySeconds(60*60*24*7)
                .and()
                .sessionManagement()
                .invalidSessionStrategy(invalidSessionStrategy())
                .maximumSessions(1)
                .expiredSessionStrategy(sessionInformationExpiredStrategy)
                .sessionRegistry(sessionRegistry())
                .and().and()
                .logout()
                .addLogoutHandler(customLogoutHandler()) // 退出清除缓存
                .logoutUrl("/user/logout") // 退出请求路径
                .logoutSuccessUrl("/mobile/page") //退出成功后跳转地址
                .deleteCookies("JSESSIONID") // 退出后删除什么cookie值
        ;
        http.csrf().disable();
        //将手机认证添加到security链上
        http.apply(mobileAuthenticationConfig);
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.authorizeRequests();
        //将所有的授权配置管理起来
        authorizeConfigureProviderManager.configure(expressionInterceptUrlRegistry);
    }

    @Bean
    public CustomLogoutHandler customLogoutHandler(){
        CustomLogoutHandler customLogoutHandler = new CustomLogoutHandler();
        customLogoutHandler.setSessionRegistry(sessionRegistry());
        return customLogoutHandler;
    }

    /**
     * 当session失效后的默认处理类
     * @return
     */
    @Bean
    public InvalidSessionStrategy invalidSessionStrategy(){
        CustomInvalidSessionHandle invalidSessionStrategy = new CustomInvalidSessionHandle();
        invalidSessionStrategy.setSessionRegistry(sessionRegistry());
        return invalidSessionStrategy;
    }


}
